package com.jingbian.cppccbackend.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jingbian.cppccbackend.entity.Activities;
import com.jingbian.cppccbackend.entity.dto.ActivityCreateDTO;
import com.jingbian.cppccbackend.entity.dto.ActivityJoinedDTO;
import com.jingbian.cppccbackend.entity.dto.EnableActivityDTO;
import com.jingbian.cppccbackend.entity.dto.MyActivitiesDTO;

import com.jingbian.cppccbackend.mapper.user.ActivitiesMapper;
import com.jingbian.cppccbackend.service.user.IActivitiesService;
import com.jingbian.cppccbackend.utils.ThreadLocalUtil;
import com.jingbian.cppccbackend.vo.CanActivitiesVO;
import com.jingbian.cppccbackend.vo.CreateActivitiesVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author pum
 * @since 2025-02-27
 */
@Service
public class ActivitiesServiceImpl extends ServiceImpl<ActivitiesMapper, Activities> implements IActivitiesService {
  @Autowired
  private ActivitiesMapper activitiesMapper;

  @Override
  public void createActivity(ActivityCreateDTO activityCreateDTO) {
    Map<String, Object> claims = ThreadLocalUtil.get();
    Activities activities = new Activities();
    BeanUtils.copyProperties(activityCreateDTO, activities);
    activities.setUserId((Integer) claims.get("uid"));
    activities.setSubmissionTime(LocalDateTime.now());
    activities.setStatus("已提交");
    activities.setTimeStatus("未开始");
    activities.setCreatedAt(LocalDateTime.now());  // 设置创建时间
    
    // 获取图片列表
    List<String> images = activityCreateDTO.getImages();
    // 进行非空判断
    if (images != null) {
        for (int i = 0; i < Math.min(images.size(), 4); i++) {
            switch (i) {
                case 0:
                    activities.setImagePath1(images.get(i));
                    break;
                case 1:
                    activities.setImagePath2(images.get(i));
                    break;
                case 2:
                    activities.setImagePath3(images.get(i));
                    break;
                case 3:
                    activities.setImagePath4(images.get(i));
                    break;
            }
        }
    }

    activitiesMapper.insertActivity(activities);
  }

  @Override
  public PageInfo<Activities> selectMyActivity(MyActivitiesDTO myActivitiesDTO) {
    // 开启分页
    PageHelper.startPage(myActivitiesDTO.getPageNum(), myActivitiesDTO.getPageSize());
    Map<String, Object> claims = ThreadLocalUtil.get();
    myActivitiesDTO.setUserId((Integer) claims.get("uid"));
    // 执行查询，使用原有的mapper方法
    List<Activities> list = activitiesMapper.getMyActivity(myActivitiesDTO);
    // 将结果封装成PageInfo对象
    return new PageInfo<>(list);

  }

  @Override
  public CreateActivitiesVO getActivities(Integer aid) {
    CreateActivitiesVO createActivitiesVO = activitiesMapper.selectActivity(aid);
    return createActivitiesVO;
  }

  @Override
  public void deleteActivity(Integer aid) {
    Map<String, Object> claims = ThreadLocalUtil.get();
    LambdaQueryWrapper<Activities> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Activities::getAid,aid)
        .eq(Activities::getUserId, (Integer) claims.get("uid"));
    activitiesMapper.delete(wrapper);
  }

  @Override
  public PageInfo<Activities> getListEnableActivities(EnableActivityDTO enableActivityDTO) {
    PageHelper.startPage(enableActivityDTO.getPageNum(), enableActivityDTO.getPageSize());
    List<Activities> list = activitiesMapper.getEnableList(enableActivityDTO);
    return new PageInfo<>(list);
  }

  @Override
  public CanActivitiesVO getCanActivityDetail(Integer aid) {
    Map<String, Object> claims = ThreadLocalUtil.get();
    Integer userId = (Integer) claims.get("uid");
    CanActivitiesVO canActivitiesVO = activitiesMapper.canActivityDetail(aid,userId);
    return canActivitiesVO;
  }

  @Override
  public PageInfo<Activities> getAlreadyJoin(ActivityJoinedDTO activityJoinedDTO) {
    Map<String,Object> claims = ThreadLocalUtil.get();
    Integer userId = (Integer) claims.get("uid");
    activityJoinedDTO.setUid(userId);
    List<Activities> list = activitiesMapper.getAlreadyJoin(activityJoinedDTO);
    return new PageInfo<>(list);
  }

    @Override
    @Transactional
    public void updateTimeStatus() {
        LocalDateTime now = LocalDateTime.now().withNano(0);
        // 使用链式操作提升性能
        updateEndedStatus(now);
        updateOngoingStatus(now);
        updateNotStartedStatus(now);
    }

    private void updateEndedStatus(LocalDateTime now) {
        LambdaUpdateWrapper<Activities> wrapper = new LambdaUpdateWrapper<>();
        wrapper.lt(Activities::getEndTime, now)
                .ne(Activities::getTimeStatus, "已结束")
                .set(Activities::getTimeStatus, "已结束");
        activitiesMapper.update(null, wrapper);
    }

    private void updateOngoingStatus(LocalDateTime now) {
        LambdaUpdateWrapper<Activities> wrapper = new LambdaUpdateWrapper<>();
        wrapper.le(Activities::getStartTime, now)
                .gt(Activities::getEndTime, now)
                .ne(Activities::getTimeStatus, "已开始")
                .set(Activities::getTimeStatus, "已开始");
        activitiesMapper.update(null, wrapper);
    }

    private void updateNotStartedStatus(LocalDateTime now) {
        LambdaUpdateWrapper<Activities> wrapper = new LambdaUpdateWrapper<>();
        wrapper.gt(Activities::getStartTime, now)
                .ne(Activities::getTimeStatus, "未开始")
                .set(Activities::getTimeStatus, "未开始");
        activitiesMapper.update(null, wrapper);
    }
}
